<?php
/**
 * 测试微信服务连接
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');

// 获取POST数据
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data) {
    echo json_encode(['success' => false, 'message' => '无效的请求数据']);
    exit;
}

// 验证必填字段
$requiredFields = ['app_id', 'app_secret'];
foreach ($requiredFields as $field) {
    if (empty($data[$field])) {
        echo json_encode(['success' => false, 'message' => '请填写所有必填字段']);
        exit;
    }
}

$appId = $data['app_id'];
$appSecret = $data['app_secret'];

// 基本验证
if (strlen($appId) < 10) {
    echo json_encode(['success' => false, 'message' => 'AppID格式不正确']);
    exit;
}

if (strlen($appSecret) < 10) {
    echo json_encode(['success' => false, 'message' => 'AppSecret格式不正确']);
    exit;
}

// 测试获取access_token
try {
    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . urlencode($appId) . '&secret=' . urlencode($appSecret);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        echo json_encode(['success' => false, 'message' => 'CURL错误：' . $error]);
        exit;
    }
    
    $result = json_decode($response, true);
    
    if ($httpCode !== 200) {
        echo json_encode(['success' => false, 'message' => 'HTTP错误：' . $httpCode]);
        exit;
    }
    
    if (isset($result['errcode']) && $result['errcode'] != 0) {
        echo json_encode(['success' => false, 'message' => '微信API错误：' . ($result['errmsg'] ?? '未知错误')]);
        exit;
    }
    
    if (isset($result['access_token'])) {
        echo json_encode(['success' => true, 'message' => '连接测试成功，配置有效']);
    } else {
        echo json_encode(['success' => false, 'message' => '响应格式错误']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => '测试失败：' . $e->getMessage()]);
}
